package com.lushixiang.service.userCheckCode.impl;

import com.lushixiang.database.UserCheckCodeDao;
import com.lushixiang.mybatis.entity.usercheckcode.UserCheckCodeEntity;
import com.lushixiang.service.userCheckCode.UserCheckCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class UserCheckCodeServiceImpl implements UserCheckCodeService {

    @Autowired
    UserCheckCodeDao userCheckCode;
    @Override
    public UserCheckCodeEntity selectByEmailAddr(String emailAddr){
        try{
            return userCheckCode.selectByEmailAddr(emailAddr);
        }catch (Exception e){
            log.error("通过邮件{}地址查询验证码记录过程中发生错误{}",emailAddr,e);
            return null;
        }
    }

    public boolean insert(String emailAddr, String code) {
        //判断是否可插入
        try{
            if(userCheckCode.selectByEmailAddr(emailAddr)!=null){
                if(!userCheckCode.deleteByEmailAddr(emailAddr)){
                    log.info("删除邮件{}已存验证码失败",emailAddr);
                    return false;
                }
            }
        }catch (Exception e){
            log.error("查询删除已存在邮件{}验证码记录过程中发生异常{}",emailAddr,e);
            return false;
        }
        UserCheckCodeEntity userCheckCodeEntity = new UserCheckCodeEntity();
        userCheckCodeEntity.setEmailAddr(emailAddr);
        userCheckCodeEntity.setCheckCode(code);
//        userCheckCodeEntity
        try{
            return userCheckCode.insert(userCheckCodeEntity);

        }catch (Exception e){
            log.error("发送异常在插入过程中{}",e.toString());
            return false;
        }
    }
}
